package com.danco.training.zaneuskaya.communication;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;





public class MessageAnalyzer {
	
	private static ObjectInputStream objectInputStream;
	private static ObjectOutputStream objectOutputStream;
	private Socket socket;

	public MessageAnalyzer (Socket socket) throws IOException{
		
		this.setSocket(socket);
		objectInputStream = new ObjectInputStream(
				socket.getInputStream());
		objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
		
		
		
	}
	
	
	public static Object analizeObject(Message m) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
	  
		String s = m.getStr();
		Object [] params = m.getParams();
		String[] worlds = s.split(";");
		
		Class<?> className = Class.forName(worlds[0]);
			
	
		Method method ;
		if (params == null){
			method = className.getDeclaredMethod(worlds[1]);
		}
		else{
			 Class<?>[] types = new Class[params.length];
		        for (int i = 0; i < params.length; i++) {
		            types[i] = params[i].getClass();
		        }
		   
		   method = className.getDeclaredMethod(worlds[1], types);
		}
		try{
		method.setAccessible(true);
		Object object = className.newInstance();
		Object res = method.invoke( object, params);

			return res;
	}
	finally{
		method.setAccessible(false);
	}
	}
	
	
		
		public static Object executeMethod (String s, Object[] object) throws IOException, ClassNotFoundException{
			Message message = new Message(s,object);
			
			objectOutputStream.writeObject(message);
			objectOutputStream.flush();
			
			Object res = objectInputStream.readObject();
			if (res == null){
				return "empty";
				
			}
			 return res;
		}




		public Socket getSocket() {
			return socket;
		}


		public void setSocket(Socket socket) {
			this.socket = socket;
		}
}
	
	

	
	
	

